// 绑定邮箱页面
const auth = require('../../../utils/auth')
const userApi = require('../../../api/user')

Page({
  data: {
    currentEmail: '', // 当前绑定的邮箱
    email: '', // 新邮箱
    verificationCode: '', // 验证码
    password: '', // 登录密码
    canSendCode: false, // 是否可以发送验证码
    canSubmit: false, // 是否可以提交
    sendingCode: false, // 是否正在发送验证码
    submitting: false, // 是否正在提交
    countdown: 0, // 倒计时
    countdownTimer: null, // 倒计时定时器
    showUnbindModal: false, // 是否显示解绑弹出层
    unbindPassword: '', // 解绑密码
    unbindSubmitting: false // 是否正在解绑
  },
  // 全局加载状态
  globalLoading: false,
  globalLoadingText: '身份验证中...',

  // 显示全局加载
  showGlobalLoading(text = '身份验证中...') {
    const app = getApp()
    app.showGlobalLoading({
      loadingText: text
    })
  },

  // 隐藏全局加载
  hideGlobalLoading() {
    const app = getApp()
    app.hideGlobalLoading()
  },

  // 更新全局加载状态
  updateGlobalLoading(data) {
    this.setData({
      globalLoading: data.globalLoading,
      globalLoadingText: data.globalLoadingText || this.data.globalLoadingText
    })
  },

  onLoad() {
    this.loadCurrentEmail()
  },

  onUnload() {
    // 清理定时器
    if (this.data.countdownTimer) {
      clearInterval(this.data.countdownTimer)
    }
  },

  // 加载当前邮箱信息
  loadCurrentEmail() {
    const userInfo = wx.getStorageSync('USER_INFO') || {}
    this.setData({
      currentEmail: userInfo.email || ''
    })
  },

  // 邮箱输入
  onEmailInput(e) {
    const email = e.detail.value
    this.setData({
      email: email,
      canSendCode: this.isValidEmail(email)
    })
    this.checkCanSubmit()
  },

  // 验证码输入
  onCodeInput(e) {
    const code = e.detail.value
    this.setData({
      verificationCode: code
    })
    this.checkCanSubmit()
  },

  // 密码输入
  onPasswordInput(e) {
    const password = e.detail.value
    this.setData({
      password: password
    })
    this.checkCanSubmit()
  },

  // 检查是否可以提交
  checkCanSubmit() {
    const { email, verificationCode, password } = this.data
    const canSubmit = this.isValidEmail(email) && 
                     verificationCode.length === 6 && 
                     password.length >= 6 && password.length <= 20
    this.setData({
      canSubmit: canSubmit
    })
  },

  // 验证邮箱格式
  isValidEmail(email) {
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
    return emailRegex.test(email)
  },

  // 验证密码格式
  validatePassword(password) {
    if (!password) {
      return '请输入密码'
    }
    if (!/^[a-zA-Z][a-zA-Z0-9_@]{5,19}$/.test(password)) {
      return '密码必须以字母开头，长度6-20位，只能包含字母、数字、下划线、@'
    }
    return null
  },

  // 发送验证码
  onSendCode() {
    const { email, sendingCode, countdown } = this.data
    
    if (sendingCode || countdown > 0) {
      return
    }

    if (!this.isValidEmail(email)) {
      wx.showToast({
        title: '请输入正确的邮箱地址',
        icon: 'none'
      })
      return
    }

    this.setData({
      sendingCode: true
    })

    // 发送验证码
    setTimeout(() => {
      this.setData({
        sendingCode: false
      })

      // 发送成功
      wx.showToast({
        title: '验证码已发送',
        icon: 'success'
      })

      // 开始倒计时
      this.startCountdown()
    }, 2000)
  },

  // 开始倒计时
  startCountdown() {
    let countdown = 60
    this.setData({
      countdown: countdown,
      canSendCode: false
    })

    const timer = setInterval(() => {
      countdown--
      this.setData({
        countdown: countdown
      })

      if (countdown <= 0) {
        clearInterval(timer)
        this.setData({
          countdown: 0,
          canSendCode: this.isValidEmail(this.data.email),
          countdownTimer: null
        })
      }
    }, 1000)

    this.setData({
      countdownTimer: timer
    })
  },

  // 提交绑定
  async onSubmit() {
    const { email, password, submitting, currentEmail } = this.data

    if (submitting) {
      return
    }

    // 验证输入
    if (!email || email.trim() === '') {
      wx.showModal({
        title: '提示',
        content: '请输入邮箱地址',
        showCancel: false,
        confirmText: '确定'
      })
      return
    }

    if (!this.isValidEmail(email)) {
      wx.showModal({
        title: '提示',
        content: '请输入正确的邮箱地址',
        showCancel: false,
        confirmText: '确定'
      })
      return
    }

    if (!password || password.trim() === '') {
      wx.showModal({
        title: '提示',
        content: '请输入登录密码',
        showCancel: false,
        confirmText: '确定'
      })
      return
    }

    // 验证密码格式
    const passwordError = this.validatePassword(password)
    if (passwordError) {
      wx.showModal({
        title: '提示',
        content: passwordError,
        showCancel: false,
        confirmText: '确定'
      })
      return
    }

    // 检查是否与当前邮箱相同
    if (currentEmail && email === currentEmail) {
      wx.showModal({
        title: '提示',
        content: '新邮箱不能与当前邮箱相同',
        showCancel: false,
        confirmText: '确定'
      })
      return
    }

    this.setData({
      submitting: true
    })

    try {
      // 获取用户信息
      const userInfo = wx.getStorageSync('USER_INFO') || {}
      const loginIdentifier = userInfo.username || userInfo.accountNumber || userInfo.phone

      if (!loginIdentifier) {
        throw new Error('用户信息不完整，请重新登录')
      }

      // 调用绑定邮箱API
      const result = await userApi.bindEmail({
        loginIdentifier: loginIdentifier,
        email: email,
        password: password
      })

      this.setData({
        submitting: false
      })

      if (result.success) {
        // 更新本地用户信息
        userInfo.email = email
        wx.setStorageSync('USER_INFO', userInfo)

        wx.showToast({
          title: currentEmail ? '邮箱更换成功' : '邮箱绑定成功',
          icon: 'success'
        })

        // 返回上一页
        setTimeout(() => {
          wx.navigateBack()
        }, 1500)
      } else {
        wx.showModal({
          title: '绑定失败',
          content: result.message || '绑定邮箱失败，请重试',
          showCancel: false,
          confirmText: '确定'
        })
      }
    } catch (error) {
      this.setData({
        submitting: false
      })

      console.error('绑定邮箱失败:', error)
      wx.showModal({
        title: '绑定失败',
        content: error.message || '网络请求失败，请检查网络连接',
        showCancel: false,
        confirmText: '确定'
      })
    }
  },

  // 解绑邮箱
  onUnbindEmail() {
    this.setData({
      showUnbindModal: true,
      unbindPassword: ''
    })
  },

  // 关闭解绑弹出层
  onCloseUnbindModal() {
    this.setData({
      showUnbindModal: false,
      unbindPassword: '',
      unbindSubmitting: false
    })
  },

  // 解绑密码输入
  onUnbindPasswordInput(e) {
    this.setData({
      unbindPassword: e.detail.value
    })
  },

  // 确认解绑
  async onConfirmUnbind() {
    const { unbindPassword, unbindSubmitting } = this.data

    if (unbindSubmitting) {
      return
    }

    // 验证密码
    if (!unbindPassword || unbindPassword.trim() === '') {
      wx.showModal({
        title: '提示',
        content: '请输入登录密码',
        showCancel: false,
        confirmText: '确定'
      })
      return
    }

    // 验证密码格式
    const passwordError = this.validatePassword(unbindPassword)
    if (passwordError) {
      wx.showModal({
        title: '提示',
        content: passwordError,
        showCancel: false,
        confirmText: '确定'
      })
      return
    }

    this.setData({
      unbindSubmitting: true
    })

    try {
      // 获取用户信息
      const userInfo = wx.getStorageSync('USER_INFO') || {}
      const loginIdentifier = userInfo.username || userInfo.accountNumber || userInfo.phone

      if (!loginIdentifier) {
        throw new Error('用户信息不完整，请重新登录')
      }

      // 调用解绑邮箱API
      const result = await userApi.unbindEmail({
        loginIdentifier: loginIdentifier,
        password: unbindPassword
      })

      this.setData({
        unbindSubmitting: false,
        showUnbindModal: false
      })

      if (result.success) {
        // 更新本地用户信息
        userInfo.email = ''
        wx.setStorageSync('USER_INFO', userInfo)

        this.setData({
          currentEmail: ''
        })

        wx.showToast({
          title: '解绑成功',
          icon: 'success'
        })
      } else {
        wx.showModal({
          title: '解绑失败',
          content: result.message || '解绑邮箱失败，请重试',
          showCancel: false,
          confirmText: '确定'
        })
      }
    } catch (error) {
            this.hideGlobalLoading();
      this.setData({
        unbindSubmitting: false
      })

      console.error('解绑邮箱失败:', error)
      wx.showModal({
        title: '解绑失败',
        content: error.message || '网络请求失败，请检查网络连接',
        showCancel: false,
        confirmText: '确定'
      })
    }
  },

  // 更换邮箱
  onChangeEmail() {
    this.setData({
      email: '',
      verificationCode: '',
      password: '',
      canSendCode: false,
      canSubmit: false
    })
  }
})
